/*
 * CommunicationSocket.cpp
 *
 *  Created on: Oct 26, 2012
 *      Author: lucas
 */

#include "CommunicationSocket.h"
#include <cstring>
#include <errno.h>
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include "SocketErrorException.h"

#define SOCKETBUFSIZE 1024

void CommunicationSocket::enviar(const std::string& msg) {
	unsigned int totalSent;
	int sizeSent;
	const char* cmsg;
	std::string mensaje;

	mensaje = msg;
	mensaje += '\n';
	cmsg = mensaje.c_str();

	sizeSent = 0;
	totalSent = 0;
	if (connected) {
		while (totalSent < mensaje.size()) {
			sizeSent = send(sockfd, cmsg + sizeSent, mensaje.size() - sizeSent, 0);
			if (sizeSent == -1 || sizeSent == 0) {
				throw SocketErrorException();
			}
			totalSent += sizeSent;
		}
	}
}

void CommunicationSocket::recibir(std::string& msg) {
	char buf[SOCKETBUFSIZE];
	int ret, recibidos;
	msg.clear();
	size_t pos;
	bool recibido = false;

	if (!connected)
		return;
	recibidos = 0;
	do {
		ret = recv(sockfd, buf, SOCKETBUFSIZE - 1, 0);
		if (ret == 0 || ret == -1) {
			throw SocketErrorException();
		}
		buf[ret] = '\0';
		msg += buf;
		pos = msg.find('\n', 0);
		if (pos != std::string::npos) {
			msg = msg.substr(0, pos);
			recibido = true;
		}
		recibidos+=ret;
	} while (!recibido);
}

bool CommunicationSocket::conectado() {
	return connected;
}

CommunicationSocket::~CommunicationSocket() {
}
